package com.atguigu.gmall.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV2;
import com.atguigu.gmall.realtime.bean.OrderDetail;
import com.atguigu.gmall.realtime.bean.OrderInfo;
import com.atguigu.gmall.realtime.bean.OrderWide;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.function.DimAsyncFunction;
import com.atguigu.gmall.realtime.util.DimUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.co.ProcessJoinFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.atguigu.gmall.realtime.common.Constant.TOPIC_DWD_ORDER_DETAIL;
import static com.atguigu.gmall.realtime.common.Constant.TOPIC_DWD_ORDER_INFO;

/**
 * @Author lzc
 * @Date 2022/4/18 14:02
 */
public class DwmOrderWideApp_Cache_Async extends BaseAppV2 {
    public static void main(String[] args) {
        new DwmOrderWideApp_Cache_Async().init("DwmOrderWideApp_Cache_Async",
                                               3003,
                                               1,
                                               "DwmOrderWideApp_Cache_Async",
                                               "DwmOrderWideApp_Cache_Async",
                                               TOPIC_DWD_ORDER_INFO, TOPIC_DWD_ORDER_DETAIL
        );
        
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       Map<String, DataStreamSource<String>> topicToStreamMap) {
        
        // 1. 事实表join
        SingleOutputStreamOperator<OrderWide> orderWideStreamWithoutDims = factsJoin(topicToStreamMap);
        // 2. 事实表与维度表"join"
        SingleOutputStreamOperator<OrderWide> orderWideStreamWithDims = factJoinDim(orderWideStreamWithoutDims);
        // 3. 把宽表数据写入到Kafka中
        writeToKafka(orderWideStreamWithDims);
    }
    
    private void writeToKafka(SingleOutputStreamOperator<OrderWide> orderWideStreamWithDims) {
        orderWideStreamWithDims
            .map(JSON::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWM_ORDER_WIDE));
    }
    
    private SingleOutputStreamOperator<OrderWide> factJoinDim(SingleOutputStreamOperator<OrderWide> orderWideStreamWithoutDims) {
      return  AsyncDataStream
            .unorderedWait(
                orderWideStreamWithoutDims,
                new DimAsyncFunction<OrderWide>() {
                    @Override
                    protected void addDIm(Jedis redisClient,
                                          Connection phoenixConn,
                                          OrderWide orderWide,
                                          ResultFuture<OrderWide> resultFuture) throws Exception {
                        //1. 补齐user_info
                        JSONObject userInfo = DimUtil.readDim(redisClient, phoenixConn, "dim_user_info", orderWide.getUser_id());
                        orderWide.setUser_gender(userInfo.getString("GENDER"));  // 获取性别
                        orderWide.calculateUserAge(userInfo.getString("BIRTHDAY"));
    
                        // 2. base_province
                        JSONObject baseProvince = DimUtil.readDim(redisClient,phoenixConn, "dim_base_province", orderWide.getProvince_id());
                        orderWide.setProvince_name(baseProvince.getString("NAME"));
                        orderWide.setProvince_iso_code(baseProvince.getString("ISO_CODE"));
                        orderWide.setProvince_area_code(baseProvince.getString("AREA_CODE"));
                        orderWide.setProvince_3166_2_code(baseProvince.getString("ISO_3166_2"));
    
                        // 3. sku
                        JSONObject skuInfo = DimUtil.readDim(redisClient,phoenixConn, "dim_sku_info", orderWide.getSku_id());
                        orderWide.setSku_name(skuInfo.getString("SKU_NAME"));
                        orderWide.setOrder_price(skuInfo.getBigDecimal("PRICE"));
    
                        orderWide.setSpu_id(skuInfo.getLong("SPU_ID"));
                        orderWide.setCategory3_id(skuInfo.getLong("CATEGORY3_ID"));
                        orderWide.setTm_id(skuInfo.getLong("TM_ID"));
    
                        // 4. spu
                        JSONObject spuInfo = DimUtil.readDim(redisClient,phoenixConn, "dim_spu_info", orderWide.getSpu_id());
                        orderWide.setSpu_name(spuInfo.getString("SPU_NAME"));
    
                        JSONObject c3 = DimUtil.readDim(redisClient,phoenixConn, "dim_base_category3", orderWide.getCategory3_id());
                        orderWide.setCategory3_name(c3.getString("NAME"));
    
                        JSONObject tm = DimUtil.readDim(redisClient,phoenixConn, "dim_base_trademark", orderWide.getTm_id());
                        orderWide.setTm_name(tm.getString("TM_NAME"));
                        
                        resultFuture.complete(Collections.singletonList(orderWide));
                    }
                },
                60,
                TimeUnit.SECONDS
            );
        
        
    }
    
    private SingleOutputStreamOperator<OrderWide> factsJoin(Map<String, DataStreamSource<String>> topicToStreamMap) {
        KeyedStream<OrderInfo, Long> orderInfoStream = topicToStreamMap
            .get(TOPIC_DWD_ORDER_INFO)
            .map(info -> JSON.parseObject(info, OrderInfo.class))
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<OrderInfo>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((info, ts) -> info.getCreate_ts())
            )
            .keyBy(OrderInfo::getId);
        
        
        KeyedStream<OrderDetail, Long> orderDetailStream = topicToStreamMap
            .get(TOPIC_DWD_ORDER_DETAIL)
            .map(info -> JSON.parseObject(info, OrderDetail.class))
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<OrderDetail>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((detail, ts) -> detail.getCreate_ts())
            )
            .keyBy(OrderDetail::getOrder_id);
        
        
        return orderInfoStream
            .intervalJoin(orderDetailStream)
            .between(Time.seconds(-5), Time.seconds(5))
            .process(new ProcessJoinFunction<OrderInfo, OrderDetail, OrderWide>() {
                @Override
                public void processElement(OrderInfo left,
                                           OrderDetail right,
                                           Context ctx,
                                           Collector<OrderWide> out) throws Exception {
                    out.collect(new OrderWide(left, right));
                }
            });
    }
}
/*

异步超时, 一般由于其他原因导致的超时
1. 检查需要的集群是否全部开启
    hdfs hbase redis zk kafka
2. 检查6张维度表是否都在, 并且都有数据
3. 重点检查dim_user_info是否4000条
4. 检查redis是否允许外部链接
    用容器: redis-server /etc/redis.conf
    原来的redis:  bind 0.0.0.0
5. 检查下redis中维度的大小写问题
6. 找我

----
打包到linux的时候, 会报异步超时, 是缺少依赖导致
    把phoenix目录下的
    cp phoenix-5.0.0-HBase-2.0-client.jar ../flink-1.13.6/lib
*/